#include "Util.h"

#ifdef _WIN32
#include "windows.h"
#endif

#include <sstream>

namespace Util
{
    void getDirectories(std::vector<std::string> &out, const std::string &directory)
    {
    #ifdef _WIN32  // Pour Windows :
        HANDLE dir;
        WIN32_FIND_DATA file_data;

        if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
            return;

        do {
            const std::string file_name = file_data.cFileName;
            const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

            if (file_name[0] == '.')
                continue;

            if (is_directory)
                continue;

            out.push_back(file_name);
        } while (FindNextFile(dir, &file_data));

        FindClose(dir);
    #else       // Pour les autres OS :
        DIR *dir;
        class dirent *ent;
        class stat st;

        dir = opendir(directory);
        while ((ent = readdir(dir)) != NULL) {
            const string file_name = ent->d_name;
            const string full_file_name = directory + "/" + file_name;

            if (file_name[0] == '.')
                continue;

            if (stat(full_file_name.c_str(), &st) == -1)
                continue;

            const bool is_directory = (st.st_mode & S_IFDIR) != 0;

            if (is_directory)
                continue;

            out.push_back(full_file_name);
        }
        closedir(dir);
    #endif
    }

    std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
    {
        std::stringstream ss(s);
        std::string item;
        while (std::getline(ss, item, delim)) {
            elems.push_back(item);
        }
        return elems;
    }
}
